<?php

namespace App\Http\Models;

use App\Observers\BosCleanObserver;
use App\Services\Utils\Bosable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\UploadedFile;


/**
 * @property int super_tag_id
 */
class ArticleTag extends Model
{
    use SafeSave,Bosable;

    const COMPANY_NEWS = 1;    // 企业动态
    const SOLUTION_CASE = 2;   // 解决方案
    const PROJECT_CASE = 3;    // 工程案例

    const TOP_TAG = 0;         // 一级的文章类别

    protected $guarded = [''];

    public $bos_columns = ['thumb'];

    protected $bos_key_prefix = 'article_type/thumb/';

    protected $table = 'article_tags';

    protected $casts = [
        'super_tag_id' => 'int'
    ];

    /**
     *  一级类别 ==> 二级类别
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany|self
     */
    public function tags()
    {
        return $this->hasMany( ArticleTag::class, 'super_tag_id','id' );
    }

    /**
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function getSubTags()
    {
        return $this->tags()->latest('sort');
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
//    public function articles()
//    {
//        return $this->belongsToMany( Article::class ,'article_pivot_tag','article_tag_id','article_id');
//
//    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function articles()
    {
        return $this->hasMany( Article::class , 'article_type_id', 'id');

    }

    /**
     *  返回一级种类的数组
     *
     * @return array
     */
    public static function getSupArticleType()
    {
        $super_tags = self::where('super_tag_id', self::TOP_TAG)
                ->pluck('name', 'id')
                ->all();

        return $super_tags;
    }

    /**
     *  检测是否有二级的类别
     *
     * @return null|Article
     */
    public function checkHasSubArticleType()
    {
        return $this->tags()->first();
    }

    /**
     *  检测二级的类别下是否有文章
     *
     * @return null|Article
     */
    public function checkHasArticle()
    {
        return $this->articles()->first();
    }

    /**
     * @param $thumb
     */
    public function setThumbAttribute($thumb)
    {
        if (is_file($thumb)) {
            $this->attributes['thumb'] = $this->uploadPostFile($thumb , $this->bos_key_prefix);
        }
    }

    /**
     * @return mixed|null
     */
    public function getThumbAttribute()
    {
        if (! $this->attributes['thumb']) return null;

        return $this->getStaticUrl($this->attributes['thumb']);
    }

    /**
     *  注册删除bosKey事件绑定
     *
     */
    protected static function boot()
    {
        parent::boot();

        /*
         * 监听bos清理事件
         */
        self::observe((BosCleanObserver::class));
    }
}
